import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:gaimon/gaimon.dart';
import 'package:get/get.dart';
import 'package:gif/gif.dart';
import 'package:sports_new/base/base_controller.dart';
import 'package:sports_new/controller/match/list/match_page_logic.dart';
import 'package:sports_new/controller/my/my_page_logic.dart';
import 'package:sports_new/controller/record/data_logic.dart';
import 'package:sports_new/controller/record/record_logic.dart';
import 'package:sports_new/controller/service/config_service.dart';
import 'package:sports_new/controller/service/resource_service.dart';
import 'package:sports_new/controller/service/scheme_service.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/utils/mode_config.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/expert/plan_page.dart';
import 'package:sports_new/view/home/home_page.dart';
import 'package:sports_new/view/match/match_page.dart';
import 'package:sports_new/view/my/my_page.dart';
import 'package:sports_new/view/record/record_page.dart';
import 'package:sports_new/controller/service/push_service.dart';
import '../utils/ali_message.dart';
import '../utils/app_config.dart';
import '../view/overlay/ads_float_widget.dart';
import '../view/record/data_page.dart';
import 'my/login_logic.dart';
import 'service/third_login_service.dart';
import 'service/umeng_service.dart';
import 'expert/plan_logic.dart';
import 'home/home_logic.dart';

class NavTab {
  const NavTab(
      {required this.name,
      required this.page,
      required this.route,
      required this.icon,
      this.doJump,
      this.onTap,
      this.getRoute});

  final String name;
  final Widget page;
  final String route;
  final String icon;
  final Function(dynamic arguments)? doJump;
  final Function()? onTap;
  final Function()? getRoute;

  static NavTab home = NavTab(
    name: "首页",
    page: const HomePage(),
    route: Routes.home,
    icon: "nav_home",
    doJump: (arguments) => Get.find<HomeLogic>().toIndex(arguments),
  );
  static const NavTab match = NavTab(
      name: "赛事", page: MatchPage(), route: Routes.match, icon: "nav_match");
  static NavTab expert = NavTab(
    name: "方案",
    page: const PlanPage(),
    route: Routes.expert,
    icon: "nav_expert",
    doJump: (arguments) => Get.find<PlanLogic>().toIndex(arguments),
    getRoute: () {
      try {
        Get.find<PlanLogic>().currentRoute;
      } catch (e) {
        log("$e");
      }
    },
  );
  static NavTab data = NavTab(
      name: "数据",
      page: const DataPage(),
      route: Routes.data,
      icon: "nav_data",
      doJump: (arguments) => Get.find<DataLogic>().toIndex(arguments));
  static const NavTab my =
      NavTab(name: "我的", page: MyPage(), route: Routes.my, icon: "nav_my");

  static List<NavTab> tabs() => [
        if (AppConfig.config.showNavigation[0]) home,
        if (AppConfig.config.showNavigation[1]) match,
        if (AppConfig.config.showNavigation[2] && ModeConfig.expert) expert,
        if (AppConfig.config.showNavigation[3] && ModeConfig.record) data,
        if (AppConfig.config.showNavigation[4]) my
      ];

  static List<String> get tabName => tabs().map((e) => e.name).toList();
  static List<String> get routes => tabs().map((e) => e.route).toList();
  static List<Widget> get pages => tabs().map((e) => e.page).toList();
  static List<String> get selectIcons =>
      tabs().map((e) => "${e.icon}_select.png").toList();
  static List<String> get unselectIcons =>
      tabs().map((e) => "${e.icon}_unselect.png").toList();
}

class NavigationLogic extends BaseController with GetTickerProviderStateMixin {
  List<String> titles = NavTab.tabName;
  static List<String> homeRoutes = NavTab.routes;
  List<Widget> pageList = NavTab.pages;
  bool showLoginFloat = true;
  List<String> unselectArray = NavTab.unselectIcons;
  List<String> selectArray = NavTab.selectIcons;
  // List<String> unselect = [];
  // List<String> select = [];
  PageController pageController = PageController();
  List<GifController> gifCList = [];
  late GifController refreshC;
  int currentIndex = 0;
  List<ResourceEntity>? theme = Get.find<ResourceService>().navigationBarTheme;
  Timer? matchTimer;
  late List<List<Widget>> navIcons;
  String? backgroundImage;
  bool matchLoading = false;
  bool matchScroll = false;
  //第一次加载底部选中为图片
  bool firstLoad = true;
  Widget? firstSelectImage;
  double? iconWidth;
  double? iconHeight;
  final thirdLoginService = Get.find<ThirdLoginService>();
  bool firstLaunch = true;
  String currentRoute = "/navigation";
  List<String> ignoreLogin = [
    Routes.vipCenter,
    Routes.secretList,
    Routes.homeExpertTop,
    Routes.data
  ];

  @override
  void onInit() {
    super.onInit();
    AliMessage().login();
    thirdLoginService.initThird();
    getInitialIndex();
    refreshC = GifController(vsync: this);
    initBottomIcon();
  }

  @override
  void onReady() async {
    super.onReady();
    User.fetchUserInfo();
    if (SpUtils.loginAuth != null) {
      Get.find<ResourceService>().getAppLoginConfig();
    }
    Get.find<ConfigService>().loadConfig();
    Get.find<SchemeService>().initScheme();
    if (Get.find<ResourceService>().bottomInitialIndex != null) {
      pageController.jumpToPage(currentIndex);
    }

    if ((Get.arguments is ResourceEntity?) || Get.arguments is ResourceEntity) {
      ResourceEntity? data = Get.arguments;
      if (data?.href != null) {
        data!.doJump();
      }
    } else if (Get.arguments is Map<String, dynamic>) {
      Get.find<PushService>().handleNotification(Get.arguments);
    }
    getRoute();
    var info = await Fluwx().getExtMsg();
    if (info.hasValue && info!.contains("{")) {
      Utils.doJump(jsonDecode(info));
    }
  }

  void getInitialIndex() {
    if (Get.find<ResourceService>().bottomInitialIndex != null) {
      String jump = Get.find<ResourceService>().bottomInitialIndex!.href!;
      int index = 0;
      if (jump == 'shouye') {
        index = pageList.indexWhere((element) => element is HomePage);
      } else if (jump == 'bisai') {
        index = pageList.indexWhere((element) => element is MatchPage);
      } else if (jump == 'caijing') {
        index = pageList.indexWhere((element) => element is PlanPage);
      } else if (jump == 'shuju') {
        index = pageList.indexWhere((element) => element is RecordPage);
      } else if (jump == 'wode') {
        index = pageList.indexWhere((element) => element is MyPage);
      }

      if(index == 0 && !Get.find<ResourceService>().hasLive){
        index = pageList.indexWhere((element) => element is PlanPage);
      }
      currentIndex = index;
    }
  }

  doMatchLoading() async {
    // throw UnimplementedError('************* need imp');
    if (!matchLoading) {
      matchLoading = true;
      matchTimer = Timer.periodic(const Duration(seconds: 2), (timer) {
        matchLoading = false;
        matchTimer?.cancel();
        refreshC.reset();
      });
    }
    final matchController = Get.find<MatchPageLogic>().getMatchController();
    await matchController.doRefresh();
  }

  onMatchPageScroll() {
    if (matchScroll) {
      return;
    }
    matchScroll = true;
    update();
  }

  doJump(
    String route, {
    dynamic arguments,
    Map<String, String>? parameters,
  }) {
    final idx = homeRoutes.indexOf(route);
    if (idx < titles.length && idx >= 0) {
      Get.until((route) => route.isFirst);
      pageController.jumpToPage(idx);
      getRoute();
      NavTab.tabs()[idx].doJump?.call(arguments);
    }
  }

  loginSuccess() {
    log('navigation login ${User.isLogin}');
    update();
  }

  onTapIndex(int index) async {
    gifCList[index].reset();
    gifCList[index].animateTo(29, duration: const Duration(milliseconds: 500));
    if (currentIndex == index) {
      switch (homeRoutes[index]) {
        case Routes.home:
          try {
            Get.find<HomeLogic>().doRefresh();
          } catch (e) {
            log(e.toString());
          }
          break;
        case Routes.match:
          doMatchLoading();
          refreshC.reset();
          refreshC.repeat(period: const Duration(seconds: 1));
          break;
        case Routes.expert:
          try {
            Get.find<PlanLogic>().doRefresh();
          } catch (e) {
            log(e.toString());
          }
          break;
        case Routes.data:
          try {
            Get.find<DataLogic>().doRefresh();
          } catch (e) {
            log(e.toString());
          }
          break;
        case Routes.my:
          try {
            Get.find<MyPageLogic>().doRefresh();
          } catch (e) {
            log(e.toString());
          }
      }
    } else {
      if (Get.find<ConfigService>().pushConfig.bottomVibration == 1) {
        if (Platform.isIOS) {
          HapticFeedback.mediumImpact();
        } else {
          Gaimon.selection();
        }
      }
      if (homeRoutes[index] != Routes.match) {
        matchScroll = false;
      }
      pageController.jumpToPage(index);
      getRoute();
      if (firstLaunch && !User.isLogin) {
        // await Future.delayed(duration);
        if (index == 1) {
          await Future.delayed(const Duration(milliseconds: 300))
              .then((value) async {
            if (Get.find<MatchPageLogic>().isLoading == false) {
              await Utils.login();
            }
          });
        } else {
          await Utils.login();
        }
        Utils.onEvent("xckdl");
        firstLaunch = false;
        User.fetchUserInfo();
        update();
      }
      // final gifController = logic.gifCList[index];
      // gifController.reset();
      // gifController.animateTo(29, duration: Duration(seconds: 1));
      // if (index == 1) {
      //   logic.gifController.reset();
      //   logic.gifController.animateTo(29, duration: Duration(seconds: 1));
      // }
    }
  }

  void getRoute() {
    currentRoute = NavTab.tabs()[currentIndex].getRoute?.call() ??
        homeRoutes[currentIndex];
    AdsFloatWidget.checkAds(currentRoute);
    update();
  }

  @override
  void getRefresh() {
    titles = NavTab.tabName;
    homeRoutes = NavTab.routes;
    pageList = NavTab.pages;
    unselectArray = NavTab.unselectIcons;
    selectArray = NavTab.selectIcons;
    initBottomIcon();
    pageController.dispose();
    pageController = PageController();
    if (currentIndex > titles.length - 1) {
      currentIndex = 1;
      pageController.jumpToPage(currentIndex);
    }
    update();
    super.getRefresh();
  }

  void initBottomIcon() {
    gifCList = [];
    gifCList =
        List.generate(pageList.length, (index) => GifController(vsync: this));
    if (theme != null && theme!.length == 13) {
      for (ResourceEntity entity in theme!) {
        if (entity.title == 'unselect_image') {
          unselectArray[(entity.sort ?? 1) - 1] = entity.imgUrl!;
        } else if (entity.title == 'select_gif') {
          selectArray[(entity.sort ?? 1) - 1] = entity.imgUrl!;
        } else if (entity.title == 'background') {
          backgroundImage = entity.imgUrl!;
        } else if (entity.title == 'icon_width') {
          iconWidth = double.tryParse(entity.content!);
        } else if (entity.title == 'icon_height') {
          iconHeight = double.tryParse(entity.content!);
        }
        if (entity.title == 'select_image' && currentIndex + 1 == entity.sort) {
          firstSelectImage = CachedNetworkImage(
              imageUrl: entity.imgUrl ?? '',
              useOldImageOnUrlChange: true,
              width: iconWidth,
              height: iconHeight);
        }
      }
    }
    navIcons = List.generate(titles.length, (index) {
      return [
        if (selectArray[index].startsWith("http")) ...[
          Gif(
              width: iconWidth,
              height: iconHeight,
              image: NetworkImage(selectArray[index]),
              autostart: Autostart.once,
              controller: gifCList[index]),
        ] else if (selectArray[index].endsWith("png")) ...[
          Image.asset(
            Utils.getImgPath(selectArray[index]),
            width: 26,
            gaplessPlayback: true,
          ),
        ] else ...[
          CachedNetworkImage(
              fadeInDuration: const Duration(),
              fadeOutDuration: const Duration(),
              width: iconWidth,
              height: iconHeight,
              imageUrl: selectArray[index],
              useOldImageOnUrlChange: true)
        ],
        if (unselectArray[index].startsWith("http")) ...[
          Gif(
              width: iconWidth,
              height: iconHeight,
              image: NetworkImage(unselectArray[index]),
              autostart: Autostart.once,
              controller: gifCList[index]),
        ] else if (selectArray[index].endsWith("png")) ...[
          Image.asset(
            Utils.getImgPath(unselectArray[index]),
            width: 26,
            gaplessPlayback: true,
          ),
        ] else ...[
          CachedNetworkImage(
              fadeInDuration: const Duration(),
              fadeOutDuration: const Duration(),
              width: iconWidth,
              height: iconHeight,
              imageUrl: unselectArray[index],
              useOldImageOnUrlChange: true)
        ]
      ];
    });
  }
}
